package common;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Created by Stuart Alex on 2021/4/12.
 */
public class DatetimeUtils {
    private static Map<String, SimpleDateFormat> dataFormats = new HashMap<>();

    public static List<String> dateRange(String dt, String format) throws ParseException {
        String startDay = dt, endDay = dt;
        if (dt.contains("-")) {
            // 处理多天的情况
            String[] splits = dt.split("-");
            if (splits.length == 1) {
                startDay = splits[0];
                endDay = yesterday(format);
            } else {
                startDay = splits[0];
                endDay = splits[1];
            }
        }
        List<String> dateRange = new ArrayList<>();
        String cursor = startDay;
        while (Integer.parseInt(cursor) <= Integer.parseInt(endDay)) {
            dateRange.add(cursor);
            cursor = dayBeforeSomeDay(cursor, -1, format);
        }
        return dateRange;
    }

    public static String yesterday(String format) {
        return dayBeforeToday(1, format);
    }

    public static String dayBeforeToday(int number, String format) {
        return hourBeforeNow(number * 24, format);
    }

    public static String hourBeforeNow(int number, String format) {
        long now = System.currentTimeMillis();
        long before = now - number * 3600 * 1000;
        return getDateFormat(format).format(new Date(before));
    }

    public static SimpleDateFormat getDateFormat(String format) {
        if (!dataFormats.containsKey(format)) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
            dataFormats.put(format, simpleDateFormat);
        }
        return dataFormats.get(format);
    }

    public static String dayBeforeSomeDay(String someDay, int number, String format) throws ParseException {
        SimpleDateFormat simpleDateFormat = getDateFormat(format);
        long someDayDate = simpleDateFormat.parse(someDay).getTime();
        long before = someDayDate - number * 3600 * 1000 * 24;
        return simpleDateFormat.format(new Date(before));
    }

    public static String nowWithFormat(String format) {
        return getDateFormat(format).format(new Date(System.currentTimeMillis()));
    }
}

